package com.woorigil.social.domain.qna.parser;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import com.woorigil.social.HtmlUtils;
import com.woorigil.social.domain.ProviderCode;
import com.woorigil.social.domain.qna.Qna;
import com.woorigil.social.domain.qna.QnaBox;

@Component (value = "coupangQnaParser")
public class CoupangQnaParser implements QnaParser {
	@Override
	public ProviderCode getProviderCode() {
		return ProviderCode.CP;
	}
	
	@Override
	public List<QnaBox> parse(String qnaUrl) {
		List<QnaBox> qnaBoxList = new ArrayList<QnaBox>();

		try {
			Document doc = Jsoup.connect(qnaUrl).timeout(1000).get();
			Elements qnaElements = doc.select(".qna_table").first().children();
			
			int count = 0;
			QnaBox qnaBox = new QnaBox(null);
			for (Element element : qnaElements) {
				if (count > 3) {
					break;
				}
				String divClass = element.attr("class");
				if ("qna_list_box".equals(divClass)) {
					count++;
					String qUser = "질문자";
					String qDate = extractDate(element.select(".qna_line_a1").text());
					String qContent = HtmlUtils.br2nl(element.select(".qna_detail_text").html());
//					System.out.println(qUser + "/" + qDate + "/" + qContent);
					qnaBox = new QnaBox(new Qna(qUser, qDate, qContent));
				} else if ("qna_list_box2".equals(divClass)) {
					String aUser = element.select(".qna_line_a1x img").attr("alt");
					String aDate = extractDate(element.select(".qna_line_a1x").text());
					String aContent = HtmlUtils.br2nl(element.select(".qna_detail_text").html());
//					System.out.println("\t" + aUser + "/" + aDate + "/" + aContent);
					qnaBox.addAnswer(new Qna(aUser, aDate, aContent));
				}
				qnaBoxList.add(qnaBox);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return qnaBoxList;
	}

	private String extractDate(String text) {
		if (StringUtils.isBlank(text)) {
			return null;
		}
		return text.substring(text.indexOf("(") + 1, text.indexOf(")"));
	}
}
